﻿/// <reference path="../../../Scripts/jquery-1.5.1-vsdoc.js" />

$(function () {
    BindChangePwdButton();
    BindDataTables();
    BindDeleteTag();
});

function CategoryEdit() {
    $(".categoryName").click(function () {
        var oldCategoryName = $.trim($(this).text());
        var editTd = $(this).parent();
        editTd.html("<input type='text' value='" + oldCategoryName + "' class='categoryEditTextBox'/>");
        $(".categoryEditTextBox").focus();

        $(".categoryEditTextBox").blur(function () {
            CategoryEditConfirm($(this).val(), oldCategoryName, editTd);
        });

        $(".categoryEditTextBox").keydown(function (event) {
            if (event.keyCode == 13) {
                CategoryEditConfirm($(this).val(), oldCategoryName, editTd);
            }
        });
    });
}

function CategoryEditConfirm(newCategoryName, oldCategoryName, editTd) {
    var categoryId = $.trim(editTd.prev().text());
    if (newCategoryName != oldCategoryName) {
        $.post("/Admin/EditCategory", { "categoryId": categoryId, "newName": newCategoryName }, function (data) {
            if (data == "Success") {
                EasyMessage("修改成功", "success", 5000);
                editTd.html(" <span class='categoryName' style='cursor: pointer;'>" + newCategoryName + "</span> ");
            }
            else {
                EasyMessage("修改失败", "error", 10000);
                editTd.html(" <span class='categoryName' style='cursor: pointer;'>" + oldCategoryName + "</span> ");
            }
        }, "json");

    }
    else {
        editTd.html(" <span class='categoryName' style='cursor: pointer;'>" + oldCategoryName + "</span> ");
    }
    //重新绑定一下
    CategoryEdit();
}

function CategoryDelete() {
    $(".deleteCategory").click(function () {
        if (confirm("确定删除这个目录？(该目录下的文章不会被删除)")) {
            var tr = $(this).parent().parent();
            var categoryID = $.trim($(this).parent().prev().prev().html());
            $.post("/Admin/DeleteCategory", { "categoryId": categoryID }, function (result) {
                if (result == "success") {
                    EasyMessage("删除成功", "success", 10000);
                    $(tr).remove();
                }
                else {
                    EasyMessage("删除失败", "error", 10000);
                }

            }, "json");
        }
    });
}

function BindDataTables() {

    if ($(".commonTable").length == 0) {
        return;
    }

    $(".commonTable").dataTable({
        "sScrollXInner": "110%",   //表格的内容宽度
        "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)  
        "bPaginate": true,  //是否显示分页
        "bLengthChange": false,  //不允许自定义页大小
        "sPaginationType": "full_numbers",
        "bFilter": true, //搜索栏
        "bSort": true, //是否支持排序功能
        "bInfo": true, //显示表格信息
        "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
        "oLanguage": {  //多语言配置
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "对不起，查询不到任何相关数据",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoEmtpy": "找不到相关数据",
            "sInfoFiltered": "", //"数据表中共为 _MAX_ 条记录)",
            "sProcessing": "正在加载中...",
            "sSearch": "搜索",
            "sUrl": "", //多语言配置文件，可将oLanguage的设置放在一个txt文件中，例：Javascript/datatable/dtCH.txt
            "oPaginate": {
                "sFirst": "第一页",
                "sPrevious": " 上一页 ",
                "sNext": " 下一页 ",
                "sLast": " 最后一页 "
            }
        }
    });
}

function TagAutoComplete() {

    var tagData = null;

    $.getJSON("/Tags/AllTags", null, function (data) {

        tagData = data;

        $('#tagContent input').autocomplete(data, {
            max: 10,    //列表里的条目数
            minChars: 1,    //自动完成激活之前填入的最小字符
            width: $("#tagContent input").width() + 2,     //提示的宽度，溢出隐藏
            scrollHeight: 300,   //提示的高度，溢出显示滚动条
            matchContains: true,    //包含匹配，就是data参数里的数据，是否只要包含文本框里的数据就显示
            autoFill: false,    //自动填充
            formatItem: function (row, i, max) {
                return row.TagName;
            },
            formatMatch: function (row, i, max) {
                return row.TagName;
            },
            formatResult: function (row) {
                return row.TagName;
            }
        }).result(function (event, row, formatted) {

            //首先检查是否有重复添加的标签
            if (!hasAddedTag(row.TagName)) {
                addTag(row.Id, row.TagName, false);
            }
        });
    });


    $("#tagContent input").keydown(function (event) {
        if (event.keyCode == 13 && !isAutoCompletePopup()) {
            var tag = $("#tagContent input").val();
            if (!hasAddedTag(tag)) {
                if (isNewTag(tag)) {
                    addTag(-1, tag, true);
                }
            }
            event.preventDefault();
        }
    });

    //检查是否已经添加相同的标签
    function hasAddedTag(tagName) {
        var hasAdded = false;
        $("#tagContent .tag").each(function () {
            var t = $(this).text().replace("...", "");
            if (t == tagName) {
                hasAdded = true;
                return;
            }
        });
        return hasAdded;
    }

    function isNewTag(tagName) {

        var isNew = true;

        for (var tag in tagData) {
            if (tagData[tag].TagName == tagName) {
                isNew = false;
                break;
            }
        }

        return isNew;
    }

    function isAutoCompletePopup() {
        var visible = $(".ac_results").css("display");
        if (typeof (visible) == "undefined" || visible == "none") {
            return false;
        }
        return true;
    }
}

//显示增加标签到页面
function addTag(tagId, tagName, isNew) {
    var tagHtml;

    var index = $("#tagContent .tag").length;

    if (isNew) {
        tagHtml = "<span class='tag'><span class='new'></span>" + tagName + "<span class='remove' title='新增标签'></span></span>"
                + "<input type='hidden' name='Tags[" + index + "].Id' value='-1'/>"
                + "<input type='hidden' name='Tags[" + index + "].TagName' value='" + tagName + "'/>";
    }
    else {
        tagHtml = "<span class='tag'>" + tagName + "<span class='remove'  title='新增标签'></span></span>"
                + "<input type='hidden' name='Tags[" + index + "].Id' value='" + tagId + "'/>"
               + "<input type='hidden' name='Tags[" + index + "].TagName' value='" + tagName + "'/>";
    }

    $("#tagContent").append(tagHtml);

    //绑定新加Tag的关闭事件
    $(".tag .remove").click(function () {
        $(this).parent().remove();
    });
    $('#tagContent input').select();
}

//修改密码按钮事件
function BindChangePwdButton() {
    $("#btnChangePwd").click(function () {
        var oldPwd = $("#oldPwd").val();
        var newPwd = $("#newPwd").val();

        if (oldPwd == "") {
            EasyMessage("请输入原密码", "error", 7000);
            return;
        }
        if (newPwd == "") {
            EasyMessage("请输入新密码", "error", 7000);
            return;
        }

        $.post("ChangePassword", { "oldPwd": oldPwd, "newPwd": newPwd }, function (data) {
            if (data == true) {
                EasyMessage("修改成功", "success", 5000);
            }
            else {
                EasyMessage("修改失败", "error", 7000);
            }
        }, "json");
    });
}

function BindDeleteTag() {
    $(".fnDeleteTag").click(function () {
        var closeButton = $(this);
        if (!confirm("确定删除该tag?")) {
            return false;
        }

        var tagId = $.trim(closeButton.parent().prev().prev().html());
        $.post("/tag/DeleteTag", { "tagId": tagId }, function (result) {
            if (result == true) {
                //                    noty({
                //                        text: "删除成功",
                //                        type: "success",  // noty type (alert, success, error)
                //                        closable: true, // enables the close button when set to true
                //                        closeOnSelfClick: false, // close the noty on self click when set to true
                //                        timeout: false,
                //                        layout: "top" // (top, topLeft, topCenter, topRight, bottom, center, bottomLeft, bottomRight)
                //                    });
                EasyMessage("删除成功", "success", 1000);
                closeButton.parent().parent().remove();
            }
            else {
                noty({
                    text: "删除失败",
                    type: "error",  // noty type (alert, success, error)
                    closable: true, // enables the close button when set to true
                    closeOnSelfClick: false, // close the noty on self click when set to true
                    timeout: false,
                    layout: "top" // (top, topLeft, topCenter, topRight, bottom, center, bottomLeft, bottomRight)
                });
            }
        }, "json");
    });
}